package controllerGoods

import (
	"github.com/gin-gonic/gin"
	dtoGoods "mxshop/app/mxshop_api/api/internal/domain/dto/goods"
	"mxshop/gmicro/pkg/common/core"
	translatorGin "mxshop/pkg/translator/gin"
	"net/http"
	"strconv"
)

type BannerForm struct {
	Image string `form:"url" json:"url" binding:"url"`
	Index int32  `form:"index" json:"index" binding:"required"`
	Url   string `form:"image" json:"image"`
}

func (gc *GoodsController) BannerList(ctx *gin.Context) {
	ret, err := gc.srv.Goods().Banner().BannerList(ctx)
	if err != nil {
		core.WriteResponse(ctx, err, nil)
		return
	}
	ctx.JSON(http.StatusOK, ret)
	return
}

func (gc *GoodsController) BannerDelete(ctx *gin.Context) {
	id := ctx.Param("id")
	idInt, err := strconv.ParseInt(id, 10, 64)
	if err != nil {
		core.WriteResponse(ctx, err, nil)
		return
	}

	if err = gc.srv.Goods().Banner().DeleteBanner(ctx, idInt); err != nil {
		core.WriteResponse(ctx, err, nil)
		return
	}
	ctx.Status(http.StatusOK)
	return
}

func (gc *GoodsController) BannerNew(ctx *gin.Context) {
	bannerForm := BannerForm{}
	if err := ctx.ShouldBindJSON(&bannerForm); err != nil {
		translatorGin.HandleValidatorError(ctx, err, gc.trans)
		return
	}

	ret, err := gc.srv.Goods().Banner().CreateBanner(ctx, &dtoGoods.BannerDTO{
		Index: bannerForm.Index,
		Image: bannerForm.Image,
		Url:   bannerForm.Url,
	})
	if err != nil {
		core.WriteResponse(ctx, err, nil)
		return
	}
	ctx.JSON(http.StatusOK, ret)
	return
}

func (gc *GoodsController) BannerUpdate(ctx *gin.Context) {
	bannerForm := BannerForm{}
	if err := ctx.ShouldBindJSON(&bannerForm); err != nil {
		translatorGin.HandleValidatorError(ctx, err, gc.trans)
		return
	}

	id := ctx.Param("id")
	idInt, err := strconv.ParseInt(id, 10, 64)
	if err != nil {
		ctx.Status(http.StatusNotFound)
		return
	}

	err = gc.srv.Goods().Banner().UpdateBanner(ctx, &dtoGoods.BannerDTO{
		Id:    idInt,
		Index: bannerForm.Index,
		Image: bannerForm.Image,
		Url:   bannerForm.Url,
	})
	if err != nil {
		core.WriteResponse(ctx, err, nil)
		return
	}
	ctx.Status(http.StatusOK)
}
